
package com.ruoyi.gisconverter.core.type;



import com.ruoyi.gisconverter.core.FeatureFactory;

import com.ruoyi.gisconverter.kml.KMLDataStore;
import com.ruoyi.gisconverter.kml.KMLDataStoreFactory;
import com.ruoyi.gisconverter.kml.KMLFeatureSource;
import org.geotools.data.FeatureSource;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.kml.v22.KML;
import org.geotools.kml.v22.KMLConfiguration;
import org.geotools.xsd.Encoder;

import java.io.*;
import java.util.HashMap;
import java.util.Map;


public class KmlFile extends FileProcess {

    @Override
    public FeatureSource readFile(File file) {
        KMLDataStore ds = null;
        try {
            Map<String, Serializable> params = new HashMap<String, Serializable>();
            params.put(KMLDataStoreFactory.FILE.key, file);

            KMLDataStoreFactory factory = new KMLDataStoreFactory();
            ds = (KMLDataStore) factory.createDataStore(params);

            return (KMLFeatureSource) ds.getFeatureSource(ds.getTypeNames()[0]);
        } catch (Exception ex) {
            throw new RuntimeException("Error while reading KML File!!!", ex);
        } finally {
            if (ds != null) {
                ds.dispose();
            }
        }
    }

    @Override
    public void writeFile(FeatureSource fs, File file) {
        try {
            FeatureFactory ff = new FeatureFactory();
            SimpleFeatureCollection kmlFeatureCollection = ff.getKmlFeatureCollection(fs);

            OutputStream out = new FileOutputStream(file);
            Encoder encoder = new Encoder(new KMLConfiguration());
            encoder.setIndenting(true);

            encoder.encode(kmlFeatureCollection, KML.kml, out);
            out.close();
        } catch (IOException ex) {
            throw new RuntimeException("Error while writing KML File!!!", ex);
        }
    }

}
